//
//  HotViewController.m
//  SugarPile
//
//  Created by Charlie. on 16/1/18.
//  Copyright © 2016年 www.lanou39.蓝鸥科技. All rights reserved.
//

#import "HotViewController.h"
#import "LClayout.h"
#import "HotCollectionViewCell.h"
#import "LCAFNetWorking.h"
#import "HotModel.h"
#import <UIImageView+WebCache.h>
#import "HotImageModel.h"
#import "LCTurnMap.h"
#import <FXBlurView.h>
#import "TaobaoWebViewController.h"
#import "HotDetailsViewController.h"
#import "Scan_VC.h"
@interface HotViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, LCLayoutItemHeightDelegate>
@property (nonatomic, retain) NSMutableArray *dataCellArr; /**< 处理数据 */
@property (nonatomic, retain) NSMutableArray *dataMapArr; /**< 轮播图数据 */
@property (nonatomic, retain) UICollectionView *collectionView; /**< 瀑布流Collection*/
@property (nonatomic, retain) UIView *mapView; /**< 轮播 */

@property (nonatomic, retain) NSIndexPath *index; /**<记录点击*/
@property (nonatomic, assign) NSInteger i; /**<记录网页加载数*/
@property (nonatomic, copy) NSString *strURL; /**<记录保存的数据网址*/

@end

@implementation HotViewController

- (void)dealloc
{
    [_collectionView release];
    [_mapView release];
    [_dataCellArr release];
    [_dataMapArr release];
    [_index release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // navigation
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(erwei)];
    
    // Collection
    [self createCollection];
    
    // 初始化
    self.i = 0;
    
    // 数据处理
    [self dataHandle];
    
    // VIew设置-235高度

    self.mapView = [[UIView alloc] initWithFrame:CGRectMake(0, -235 * H, WIDTH, 200 * H)];
//    self.View1.backgroundColor = [UIColor blackColor];
    // VIew放到CollectionView上
    [self.collectionView addSubview:self.mapView];
    // 下拉刷新
    [self refresh];
    
    // 上拉加载
    [self loading];
    
    // 轮播图
    [self LBT];
//    NSLog(@"%@", _dataArr);
//    NSDateComponents *_comps = [[NSDateComponents alloc] init];
//    [_comps setDay:16];
//    [_comps setMonth:1];
//    [_comps setYear:2016];
//    NSCalendar *gregorian = [[NSCalendar alloc]
//                             initWithCalendarIdentifier:NSGregorianCalendar];
//    NSDate *_date = [gregorian dateFromComponents:_comps];
//    NSDateComponents *weekdayComponents =
//    [gregorian components:NSWeekdayCalendarUnit fromDate:_date];
//    NSInteger _weekday = [weekdayComponents weekday] - 1;
//    NSLog(@"_weekday::%ld",_weekday);
    
    [self.mapView release];
}
-(void)erwei
{
    Scan_VC *scan = [[Scan_VC alloc] init];
    UINavigationController *ac = [[UINavigationController alloc] initWithRootViewController:scan];

    [self presentViewController:ac animated:YES completion:^{
        
    }];
}
#pragma mark - 轮播
- (void)LBT
{
    
    [LCAFNetWorking GETWithURL:@"http://203.80.144.212/napi/ad/banner/week/?platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522508622%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=67&platform_name=Android&locale=zh&adid=ANA001&app_code=nayutas" completion:^(id result) {
        NSArray *arr = result[@"data"];
        self.dataMapArr = [HotImageModel modelHanderWithArray:arr];
        
        NSMutableArray *TurnMapArr = [NSMutableArray array];
        for (NSInteger i = 0; i<_dataMapArr.count; i++) {
            HotImageModel *m = _dataMapArr[i];
            NSString *k = m.image_url;
            [TurnMapArr addObject:k];
            //            NSLog(@"~~%@", m.image_url);
        }
        LCTurnMap *image = [[LCTurnMap alloc] initWithFrame:CGRectMake(0, 0, WIDTH , 235 * H) URLArr:TurnMapArr timeInterval:2 Yuandianframe:CGRectMake(0, 200, 235, 30)];
        
        // 轮播图添加Label
//        UILabel *Label = [[UILabel alloc] initWithFrame:CGRectMake(10, 170, 300, 30)];
//        Label.backgroundColor = [UIColor yellowColor];
//        [image addSubview:Label];
//        NSLog(@"%@", arr[1][@"description"]);
        [self.mapView addSubview:image];
        [image release];
    }];
}
#pragma mark - Collection
- (void)dataHandle{
    self.strURL = @"http://203.80.144.213/napi/index/hot/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522267372%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=67&start=0&platform_name=Android&locale=zh&app_code=nayutas";
    [LCAFNetWorking GETWithURL:_strURL completion:^(id result) {
      
        NSArray *arr = result[@"data"][@"object_list"];
        
        self.dataCellArr = [HotModel modelHanderWithArray:arr];
        
        [self.collectionView reloadData];
    }];
    
}
- (void)createCollection
{
    
//            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
//            layout.itemSize = CGSizeMake(100, 100);
    
    LClayout *layout = [[LClayout alloc] init];
    layout.columcounts = 2;
    layout.columSpace = 15;
    layout.rowSpace = 15;
    layout.edgeInsets = UIEdgeInsetsMake(15, 15, 15, 15);
    // 代理人
    layout.delegate = self;
//    layout.headerReferenceSize = CGSizeMake(375, 200);
    // coleation 属性
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    // 协议
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    // 设置上边距 用来放置 伦布图
    _collectionView.contentInset = UIEdgeInsetsMake(235 * H, 0, 0, 0);
//    FXBlurView *mm = [[FXBlurView alloc]initWithFrame:self.view.bounds];
//    [self.view addSubview:mm];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = [UIColor floralWhite];
    // 重用池
    [_collectionView registerClass:[HotCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
//    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [_collectionView release];
    [layout release];
}
#pragma mark - Collection
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return _dataCellArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (self.dataCellArr.count != 0) {
        
        HotModel *m = _dataCellArr[indexPath.item];
//        self.index = indexPath;
        // m 传入cell;
        cell.model = m;
        //    // 判断 数据 如果有则 在cell上赋值
        // 用户交互
        if (![m.icon_url isEqualToString:@""]) {
            cell.carView.userInteractionEnabled = YES;
            [cell.carButton addTarget:self action:@selector(dian) forControlEvents:UIControlEventTouchUpInside];
            
        }
    }
//
    
    
    return cell;
}
- (void)dian
{
    NSLog(@"点点点");
    TaobaoWebViewController *taobaoVC = [[[TaobaoWebViewController alloc] init] autorelease];
    HotModel *m = _dataCellArr[_index.item];
    taobaoVC.urlModel = m;
    taobaoVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:taobaoVC animated:YES];
    
}
// 点击跳转方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotDetailsViewController *hotDetailsVC = [[[HotDetailsViewController alloc] init] autorelease];
    hotDetailsVC.hidesBottomBarWhenPushed = YES;
    HotModel *m = _dataCellArr[indexPath.item];
//    NSLog(@"%ld", _index.item );
    hotDetailsVC.detailsId = m.ID;
    [self.navigationController pushViewController:hotDetailsVC animated:YES];
}
//#pragma mark - layout高度计算方法
-(CGFloat)layout:(LClayout *)layout heightForItemAtindexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    // tw/wh = iw/ih

    HotModel *m = _dataCellArr[indexPath.item];
    CGFloat h = width * m.height.doubleValue / m.width.doubleValue;
    
    //文本高度
    CGFloat textHeight = [HotCollectionViewCell heightWithText:m.msg Size:9];
    //判断文本框 高度是否 超过 15.51 * 6 的 高度(6行的高度)
    if (textHeight >= 15.51 * 6) {
        //设置最大文本框行数 为 6行;
        textHeight = 15.51 * 6;
    }
    // 每个cell的高度 由 图片高度 和 文本高度  + 其他控件高度(80)
    return h + textHeight + 80;
}
#pragma mark - 上拉加载
- (void)loading
{
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
       // 延迟两秒
//       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        _i += 24;
           NSString *url = [_strURL stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%ld", _i]];
        NSLog(@"%@", url);
           [LCAFNetWorking GETWithURL:url completion:^(id result) {
               
               NSArray *temp = result[@"data"][@"object_list"];
               NSArray *aTemp = [HotModel modelHanderWithArray:temp];
               for (HotModel *m in aTemp) {
                   [self.dataCellArr addObject:m];
               }
               NSLog(@"%ld", _i);
              
               // 刷新
               [_collectionView reloadData];
           }];
           [_collectionView.mj_footer endRefreshing];
           
//       });
        
    }];
    _collectionView.mj_footer = footer;
}
#pragma mark - 下拉刷新
- (void)refresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //延迟2秒
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
//                       dispatch_get_main_queue(),^{
        
                           // 刷新
                           _i = 24;
                           [self.dataCellArr removeAllObjects];
                           [self dataHandle];
                           //新版本是 MJ_header
                           [self.collectionView.mj_header endRefreshing];
//                       });
    }];
    self.collectionView.mj_header = header;
    //    header.stateLabel.font = [UIFont systemFontOfSize:12];
}
// 通过协议方法 让外面数据数组刷新是 同时让自定义lyout arr刷新
- (void)array:(NSMutableArray *)arr
{
    if (_dataCellArr.count == 0) {
        [arr removeAllObjects];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
